package org.linlinjava.litemall.brand.config;

import org.linlinjava.litemall.brand.annotation.LoginUser;
import org.linlinjava.litemall.brand.service.UserTokenManager;
import org.linlinjava.litemall.brand.web.BrandAuthController;
import org.linlinjava.litemall.brand.web.BrandController;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

    @Component
    class SessionHandlerInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*            System.out.println(request.getSession().getId());
            Object token1 = request.getSession().getAttribute("token");
            if (token1 != null) {
                String tokenSave = token1.toString();
                String token = request.getHeader("token");
                if (token.equals(tokenSave)) {
                    return true;
                } else {
                    response.setCharacterEncoding("utf-8");
                    response.setContentType("application/json; charset=utf-8");
                    PrintWriter out = response.getWriter();
                    out.write("{\"code\":401,\"note\":\"您的登陆状态已经失效，请重新登陆\"}");
                    //response.sendRedirect("");
                    return false;
                }
            }
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("{\"code\":401,\"note\":\"您未登录，请先登陆\"}");
            //response.sendRedirect( "/");
            return false;*/
          String token = request.getHeader("token");
          Integer userId = UserTokenManager.getUserId(token);
          if (userId!=null){
              return true;
          }else {
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json; charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.write("{\"code\":401,\"note\":\"请登陆\"}");
            return true;
          }
//在处理器之前执行的前置方法，这样 Spring MVC 可以在进入处理器前处理一些方法。注意，他会返回一个 boolean 值，会影响到后面Spring MVC 的流程。
        }
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
// controller 方法处理完毕，页面渲染之前调用此方法。比如可以在这里将渲染的视图名称更改为其他视图。
        }
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// 页面渲染完毕后调用此方法，通常用来接触某些资源。
        }
    }

